package com.itheima.tliassystem.aspect;


import com.itheima.tliassystem.mapper.OperateLogMapper;

import entity.OperateLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itheima.tliassystem.uile.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
public class OperationAspect {
    @Autowired
    OperateLogMapper operateLogMapper;
    @Autowired
    HttpServletRequest request; //注入request 对象 在ioc容器中
    @Around("@annotation(com.itheima.tliassystem.aspect.OperateLog)")
    public Object recordOperation(ProceedingJoinPoint PJP) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceed = PJP.proceed();//执行目标的方法
        long end = System.currentTimeMillis();
        //记录日志的操作 本质上就是向日志中插入一条数据
        //1封装日志对象
        OperateLog operateLog1 =  new OperateLog();
        operateLog1.setOperateTime(LocalDateTime.now());
        operateLog1.setClassName(PJP.getTarget().getClass().toString());
        operateLog1.setCostTime(end - start);
        operateLog1.setMethodName(PJP.getSignature().getName());
        operateLog1.setMethodParams(Arrays.toString(PJP.getArgs()));
        operateLog1.setReturnValue(proceed+"");

       String token = request.getHeader("token");
        Integer empId = (Integer) JwtUtils.parseJWT(token).get("empId");
        operateLog1.setOperateUser(empId);
        operateLogMapper.insert(operateLog1);
        return proceed;

    }

}
